import { Component, Inject } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { Keyboard } from '@ionic-native/keyboard';

import { Register } from '../../../providers/entity/user.model';
import { Subscription } from 'rxjs/Subscription';

// util service
import { AlertService } from '../../../providers/utils/alert.service';

/**
 * 注册
* */
@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html'
})
export class RegisterPage {

  // 显示头部
  private hideTitle: boolean= false;
  private KeyboardShow: Subscription;
  private KeyboardHide: Subscription;
  // 注册
  private register: Register= {
    username: '',
    password: '',
    msgCode: '',
  };
  // 是否显示密码
  private switchover: any = {
    type: 'password',
    status: true
  };

  // 定时器
  private timer: any;
  // 倒计时
  private countdown: number= 0;

  constructor(
    @Inject('auth') private authService,
    private keyboard: Keyboard,
    private alertCtrl: AlertService,
    private navCtrl: NavController,
  )
  {}
  /*** 页面进入
   * */
  ionViewWillEnter()
  {
    this.initSubscription();
  }
  /*** 页面离开
   * */
  ionViewWillLeave()
  {
    this.removeSubscription();
  }
  /*** 初始化监听键盘
   * */
  private initSubscription(): void
  {
    this.KeyboardShow= this.keyboard.onKeyboardShow().subscribe(data=>{
      if(!data) return;
      this.hideTitle= true;
    });

    this.KeyboardHide= this.keyboard.onKeyboardHide().subscribe(data=>{
      if(!data) return;
      this.hideTitle= false;
    });

  }
  /*** 移除监听
   * */
  private removeSubscription(): void
  {
    if(typeof this.KeyboardShow !== 'undefined')
      this.KeyboardShow.unsubscribe();

    if(typeof this.KeyboardHide !== 'undefined')
      this.KeyboardHide.unsubscribe();
  }

  /*** 打开定时器
   * */
  public startInterval(): void
  {
    this.timer = setInterval(()=>{
      this.countdown--;
      if(this.countdown === 0)
      {
        clearInterval(this.timer);
        this.timer = null;
      }
    },1000);
  }


  /*** 清除用户名
   * */
  public clearUserName(): void
  {
    this.register.username='';
  }

  /*** 切换密码显示方式
   * */
  public switchoverPassword(obj: any): void
  {
    if(!obj.type) return;
    this.switchover = {
      type: obj.type==='text'? 'password': 'text',
      status: !obj.status
    }

  }

  /*** 清除输入
   * */
  public clearMsgCode()
  {
    this.register.msgCode = '';
  }

  /** 执行再次发送验证码
   * */
  public executeGetAgain(): void
  {
    if(!this.register.username)
    {
      this.alertCtrl.createAgreeAlert('手机号不为空');
      return;
    }
    this.countdown = 60 ;
    this.startInterval();
    this.authService.checkRegister(this.register);
  }

  /*** 执行注册
  * */
  public executeRegister(): void
  {
    this.authService.executeRegister(this.register,this.navCtrl);
  }

}
